﻿#include "messageservice.h"
#include "user.h"
#include <QMessageBox>

MessageService::MessageService(QObject *parent) : QObject(parent)
{

}

void MessageService::getMessages(QWidget *widget){
    manager = new MessageNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        Q_UNUSED(message)
        QJsonArray messageArr = data.value("messages").toArray();
        QList<Message*> messages;
        for(QJsonValue obj:messageArr){
            Message *message = new Message();
            message->loadFromJsonObject(obj.toObject());
            messages.append(message);
        }

        emit this->getMessagesSuccess(messages);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });


    manager->getMessages(User::getUsername());
}

void MessageService::getImportMessage(
        QWidget *widget,
        QPushButton *button,
        int ticketAdjustType,
        int type){
    manager = new MessageNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        button->setEnabled(true);
        QMessageBox::warning(widget, "警告", message);
    });

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        button->setEnabled(true);
        Q_UNUSED(message);
        QJsonArray messageArr = data.value("importMessages").toArray();
        QList<Message*> messages;
        for(QJsonValue obj:messageArr){
            Message *message = new Message();
            message->loadFromJsonObject(obj.toObject());
            messages.append(message);
        }

        emit this->getImportMessagesSuccess(messages);
    });

    button->setEnabled(false);
    manager->getImportMessages(User::getUsername(), ticketAdjustType, type);
}
